package fi.saarinen.loader.elf;

import java.io.FileInputStream;
import java.io.IOException;

/**
 * Support code for big-endian machine.
 * 
 * @author jsaarinen
 */
public class IO
{
  public static byte[] mmap(String fileName) throws IOException
  {
    FileInputStream fileInputStream = new FileInputStream(fileName);
    byte[] data = new byte[fileInputStream.available()];
    fileInputStream.read(data);
    fileInputStream.close();
    return data;
  }
  
  public static int readAddr(byte[] mem, int offset)
  {
    return readWord(mem, offset);
  }
  
  public static int readWord(byte[] mem, int offset)
  {
    if ((offset & 0x3) > 0)
    {
      throw new IllegalArgumentException("Invalid offset: " + offset);
    }
    int x = 0;
    x |= mem[offset + 0];
    x <<= 8;
    x |= mem[offset + 1];
    x <<= 8;
    x |= mem[offset + 2];
    x <<= 8;
    x |= mem[offset + 3];
    return x;
  }

  public static short readHalf(byte[] mem, int offset)
  {
    if ((offset & 0x1) > 0)
    {
      throw new IllegalArgumentException("Invalid offset: " + offset);
    }
    int x = 0;
    x |= mem[offset + 0];
    x <<= 8;
    x |= mem[offset + 1];
    return (short)x;
  }
  
  public static int readOff(byte[] mem, int offset)
  {
    return readWord(mem, offset);  
  }
    
  public static int readSWord(byte[] mem, int offset)
  {
    return readWord(mem, offset);  
  }

  public static int readUChar(byte[] mem, int offset)
  {
    return mem[offset];  
  }
}
